import os
import maven
import cmake
import meson
import autotools
from autoconf_depends import AutoconfDepends
import sys


def process(dir, filename):
    lowername = filename.lower()
    filename = dir + filename
    if lowername == 'cmakelists.txt':
        print('target file : ' + filename)
        cmake.parse(filename)
        cmake.save_cmake(dir)
    elif lowername == 'makefile.am' or lowername == 'configure.ac':
        print('target file : ' + filename)
        exit(0)
    elif lowername == 'meson.build':
        print('target file : ' + filename)
        meson.parse(filename)
        meson.save_meson(dir)
    elif lowername == 'pom.xml':
        print('target file : ' + filename)
        maven.parse(filename)
    else:
        sys.stderr.write("Error : Not a target file")


if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.stderr.write("Error : Need project path parameter")
        exit(0)
    path = sys.argv[1]
    valid_name = ['cmakelists.txt', 'makefile.am', 'configure.ac', 'meson.build', 'pom.xml']

    if os.path.isfile(path):
        index = path.rfind(os.sep) + 1
        process(path[:index], path[index:])
    elif os.path.isdir(path):
        files = [f for f in os.listdir(path) if not f.startswith('.') and f.lower() in valid_name]
        if not files:
            sys.stderr.write("Error : No target file in this path")
        else:
            if not path.endswith(os.sep):
                path = path + os.sep
            process(path, files[0])
    else:
        sys.stderr.write("Error : Invalid parameter")

    # autotools.parse('C:\project\construct\Makefile.am')
    # autotools.save_auto()

    # parser = AutoconfDepends()
    # parser.load_configure_ac("C:\project\construct\configure.ac")
    # parser.parse_macros()
    # parser.save_macros()
    # parser.parse_conditions()
    # parser.save_conditions()
    # print(result)
